package com.example.drzhang.oengldemo.render;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;

import com.example.drzhang.oengldemo.R;
import com.example.drzhang.oengldemo.data.Mallet;
import com.example.drzhang.oengldemo.data.Table;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * @author drzhang
 * @date 2018.1.6
 * 渲染器
 */
public class NewGLRender implements GLSurfaceView.Renderer {

    public static final String TAG = NewGLRender.class.getSimpleName();

    private Context mContext;
    private float[] projectionMatrix = new float[16];
    private float[] modelMatrix = new float[16];

    private Table mTable;
    private Mallet mMallet;

    private TextureShaderProgram mTextureShaderProgram;
    private ColorShaderProgram mColorShaderProgram;

    private int texture;

    public NewGLRender(Context context) {
        this.mContext = context;
    }

    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {

        GLES20.glClearColor(0.0f, 0f, 0f, 0f);

        mTable = new Table();
        mMallet = new Mallet();

        mTextureShaderProgram = new TextureShaderProgram(mContext);
        mColorShaderProgram = new ColorShaderProgram(mContext);

        texture = TextureHelper.loadTexture(mContext,R.drawable.air_hockey_surface);

    }

    @Override
    public void onSurfaceChanged(GL10 gl10, int width, int height) {
        GLES20.glViewport(0, 0, width, height);

        MatrixHelper.perspectiveM(projectionMatrix,45,(float) width/(float) height,1f, 10f);
        //将modelMatrix置为单位矩阵
        Matrix.setIdentityM(modelMatrix,0);
        //将该单位矩阵沿着z轴平移-2
        Matrix.translateM(modelMatrix,0,0f,0f, -2.5f);
        Matrix.rotateM(modelMatrix,0,-60f,1f,0f,0f);
        float[] temp = new float[16];
        Matrix.multiplyMM(temp,0,projectionMatrix,0,modelMatrix,0);
        System.arraycopy(temp,0,projectionMatrix,0,temp.length);

    }

    @Override
    public void onDrawFrame(GL10 gl10) {

        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        mTextureShaderProgram.userProgram();
        mTextureShaderProgram.setUniforms(projectionMatrix,texture);
        mTable.bindData(mTextureShaderProgram);
        mTable.draw();

        mColorShaderProgram.userProgram();
        mColorShaderProgram.setUniforms(modelMatrix,texture);
        mMallet.bindData(mColorShaderProgram);
        mMallet.draw();
    }
}
